package com.xiaomili.halfsugar.utils;

import android.content.Context;
import android.os.Handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/7/14.
 */
public class OKHttpUtils {
    private static OKHttpUtils mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mHandler = new Handler();

    private OKHttpUtils(Context context) {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        int cacheSize = 10 << 20;//相当于10*2^20=10M;
        mOkHttpClient = builder.cache(new Cache(context.getCacheDir(), cacheSize))//设置缓存大小
                .connectTimeout(15, TimeUnit.SECONDS)//连接时间
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .build();

    }

    public static OKHttpUtils newInstance(Context context) {
        if (mInstance == null) {
            synchronized (OKHttpUtils.class) {
                if (mInstance == null) {
                    mInstance = new OKHttpUtils(context);
                }
            }
        }
        return mInstance;
    }

    //=======================================================//
    //GET异步请求方式
    //=======================================================//
    public void obtainDataAsyncByGet(String url, final MyCallback callback) {

        Request request = new Request.Builder()
                .url(url)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handleFailure(e, callback);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                handleSuccess(result, callback);
            }
        });
    }

    //=======================================================//
    //POST异步请求方式
    //=======================================================//

    public void obtainDataAsyncByPost(String url, HashMap<String, String> param, final MyCallback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        if (param != null && param.size() != 0) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handleFailure(e, callback);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                handleSuccess(result, callback);
            }
        });
    }

    //失败时回调
    private void handleFailure(final IOException e, final MyCallback listener) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                listener.onFailure(e);
            }
        });
    }

    //成功时回调
    private void handleSuccess(final String result, final MyCallback listener) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                listener.onResponse(result);
            }
        });
    }

    //定义一个接口在主线程回调
    public interface MyCallback {
        void onFailure(IOException e);

        void onResponse(String result);
    }
}
